package sbc.ejb3.dao;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;

import org.apache.log4j.Logger;

import sbc.ejb3.Platine;
import sbc.ejb3.Sensor;

@Stateless
public class TimerBean implements TimerRemote {
	
	private static Logger log = Logger.getLogger(TimerBean.class);
	
	@Resource private TimerService timerService;
	
	@EJB private DistributorRemote distributor;
	
//	@EJB private PlatineRemote platineRemote;			
//	@EJB private SensorRemote sensorRemote;
//	
//	@Resource(mappedName="TopicConnectionFactory")
//	private TopicConnectionFactory topicConnectionFactory;
//	
//	@Resource(mappedName="topic/qsTopic")
//	private Topic qsTopic;
//	
//	@Resource(mappedName="topic/montageTopic")
//	private Topic montageTopic;
	

	public void scheduleTimerBean(long initialDuration, long intervalDuration) {
		log.info("scheduleTimerBean");
		
		/*
		 * set default values (if args == 0)
		 */
		initialDuration = initialDuration != 0 ? initialDuration : 1000 * 10; // 10 secs
		intervalDuration = intervalDuration != 0 ? intervalDuration : 1000 * 30; // 30 secs
		log.info("initialDuration:" + initialDuration);
		log.info("intervalDuration:" + intervalDuration);
		
		/*
		 * cancel any running timers
		 */
		this.cancelTimers();
		
		/*
		 * create a Timer
		 */
		timerService.createTimer(initialDuration, intervalDuration, "TimerBean");
	}
	
	@Timeout
	public void timeout(Timer timer) {
		log.info("timeout");
		
		distributor.forwardToQsTopic();
		distributor.forwardToMontageTopic();	
		distributor.forwardToLogisticQueue();	
		
		
		/*
		 * check for ungemesseneSensoren
		 * possibly forward to qsTopic
		 */
//		List<Sensor> ungemesseneSensoren = sensorRemote.getUngemesseneSensoren();
//        for (Sensor s : ungemesseneSensoren) {
//        	log.info("Ungemessener Sensor: " + s);
//        
//        	try {
//				log.info("forwarding sensor to qsTopic");
//				
//				log.info("Creating connection");
//				TopicConnection connection = topicConnectionFactory.createTopicConnection();
//
//				try {
//					log.info("Creating session");
//					TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
//					
//					log.info("Creating publisher");
//					TopicPublisher sender = session.createPublisher(qsTopic);
//
//					log.info("Creating message");					
//					ObjectMessage topicObjectMessage = session.createObjectMessage(s);
//
//					log.info("Sending message");
//					sender.send(topicObjectMessage);
//				}
//				finally {
//					connection.close();
//				}
//			} 
//        	catch (JMSException e) {
//				e.printStackTrace();
//			}        
//        }
//		
//		/*
//		 * check for gemesseneSensoren and unmontiertePlatinen
//		 * possibly forward to montageTopic
//		 */
//		List<Sensor> gemesseneSensoren = sensorRemote.getGemesseneSensoren();
//        for (Sensor s : gemesseneSensoren)	
//        	log.info("Gemessener Sensor: " + s);
//        
//		List<Platine> unmontiertePlatinen = platineRemote.getUnmontiertePlatinen();
//        for (Platine p : unmontiertePlatinen)	
//        	log.info("Unmontierte Platine: " + p);
//        
//        if (gemesseneSensoren.size() >= 2 && unmontiertePlatinen.size() >= 1) {
//        	int montageIterations = 0;
//        	if (unmontiertePlatinen.size() < gemesseneSensoren.size() / 2) {
//        		montageIterations = unmontiertePlatinen.size();
//        	}
//        	else {
//        		montageIterations = gemesseneSensoren.size() / 2;
//        	}
//        	log.info("montageIterations: " + montageIterations);
//        	
//        	for (int i=0; i < montageIterations; i++) {
//	        	try {
//					log.info("forwarding platine and 2x sensor to montageTopic");
//
//					Platine platine = unmontiertePlatinen.get(i);
//					Sensor sensor1  = gemesseneSensoren.get(2*i);
//					Sensor sensor2  = gemesseneSensoren.get(2*i+1);
//					log.info("platine: " + platine);
//					log.info("sensor1: " + sensor1);
//					log.info("sensor2: " + sensor2);
//					
//					log.info("Creating connection");
//					TopicConnection connection = topicConnectionFactory.createTopicConnection();
//	
//					try {
//						log.info("Creating session");
//						TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
//						
//						log.info("Creating publisher");
//						TopicPublisher sender = session.createPublisher(montageTopic);
//	
//						log.info("Creating message");					
//						MapMessage mapMessage = session.createMapMessage();
//						mapMessage.setInt("PlatineId", platine.getId());
//						mapMessage.setInt("Sensor1Id", sensor1.getId());
//						mapMessage.setInt("Sensor2Id", sensor2.getId());
//						
//						log.info("Sending message");
//						sender.send(mapMessage);
//					}
//					finally {
//						connection.close();
//					}
//				} 
//	        	catch (JMSException e) {
//					e.printStackTrace();
//				}        
//        	}
//        }		
	}
	
	public void cancelTimers() {
		log.info("cancelTimers");
		
		/*
		 * cancel any running TimerBean timers
		 */
		for (Object obj : timerService.getTimers()) {
			Timer timer = (Timer)obj;
			if (timer.getInfo().equals("TimerBean")) {
				log.info("canceling old timer");
				timer.cancel();
			}
		}
	}
}
